<?php

/**
 * IndexController - The Base controller class
 * 
 * @author seraph.liujb
 * @version 
 */

class BaseController extends Zend_Controller_Action {
    /**
     * 路由分发器前置处理区域
     *
     * @return void
     * @author seraph.liujb
     */
    public function preDispatch() {
    	parent::preDispatch();
    }
    
    /**
     * 初始化
     *
     */
    public function init() {
    	parent::init();
    	//载入logger
    	$this->logger = Zend_Registry::get('logger');
    	//指定默认view helper目录
		$this->view->addHelperPath('../application/_default/views/helpers');
		//设置页面标题分隔符
		$this->view->headTitle()->setSeparator(' | ');
		//设置整站通用标题
		$this->view->headTitle('seraph-common','PREPEND');
    }
    
	/**
	 * 禁止视图，主要用于Ajax类的调用
	 *
	 * @param boolean $layout = true 禁止布局调用
	 * @param boolean $layout = true 禁止视图调用
	 * @return void
	 * @author seraph.liujb
	 */
	public function disableView($layout = true, $view = true) {
		if ($layout) {	
			$this->_helper->layout()->disableLayout();
		}
		if ($view) {
			$this->_helper->viewRenderer->setNoRender();
		}
	}
	
    /**
     * 快速获取用户参数，包括request get post
     *
     * @param string $param 参数名称
     * @param mixed $default 默认值
     * @return mixed
     */
    protected function gr($param, $default = null)
    {
    	return $this->getRequest()->getParam($param, $default);
    }
    /**
     * 快速获取session值
     *
     * @param string $ns
     * @param string $param 如果该项为null，则返回$ns的Zend_Session_Namespace对象
     * @param mixed $default
     * @return mixed
     */
    protected function gs($ns, $param = null, $default = null)
    {
    	if ($param == null)
    	{
    		return new Zend_Session_Namespace($ns);
    	}
   		$s = new Zend_Session_Namespace($ns);
		if (isset($s->$param))
		{
			return $s->$param;
		}
   		return $default;
    }
    
    /**
     * 快速获取cookie值
     *
     * @param string $param
     * @param mixed $default
     * @return mixed
     */
    protected function gc($param, $default = null)
    {
    	if (isset($_COOKIE[$param]))
    		return $_COOKIE[$param];
    	else 
    		return $default;
    }
    
    /**
     * 快速设置cookie值
     *
     * @param string $param 参数名
     * @param string $value 设置值
     * @param integer $expires 有效时间，默认为10小时，3600*10
     * @param string $path 有效路径，如'/','/foo/'
     * @param string $domain 有效域名，如'foo.com','www.foo.com'
     * @return boolean
     */
    protected function sc($param, $value, $expires = 36000, $path = null, $domain = null)
    {
    	return setcookie($param, $value, time()+$expires, $path, $domain);
    }
    /**
     * 判断提交是否为Post
     *
     * @return boolean
     */
    protected function isPost()
    {
    	if ($_SERVER['REQUEST_METHOD'] == 'POST')
    		return true;
    	else 
    		return false;
    }
    /**
     * 判断提交是否为Get
     *
     * @return boolean
     */
    protected function isGet()
    {
    	if ('GET' == $_SERVER['REQUEST_METHOD'])
    		return true;
    	else 
    		return false;
    }
	/**
	 * 封装JS的alert提示框
	 * 
	 * @author Will
	 */
	function alert($msg,$redirect_url = ''){
		echo "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />";
		if ($redirect_url) {
			if('history.back()' == $redirect_url){
				echo "<script>alert(\"{$msg}\");history.back();</script>";
			}else {
				echo "<script>alert(\"{$msg}\");location.href=\"{$redirect_url}\";</script>";
			}
		}else {
			echo '<script language="javascript">alert("'.$msg.'")</script>';
		}
		exit;		
	}
    
    /**
     * 取得角色
     *
     * @author IDKin.COM
     * @return string 返回角色名字符串
     */
    public function getRole(){
    	return 'guest';
    }
    

    
	/**
     * 判断ASO登录状态是否有效，并进行登录操作
     * 
     */
    public function asoLogin()	{
    	$asotName = 'ASOT_' . md5($_SERVER['HTTP_HOST']);
    	//判断ASO域空间cookie.ASOT是否存在
    	if ($this->checkAsoTicket($asotName)) {
	    	//ASOT存在并有效，转向App页面
    		return true;
    	}
	    //判断SSOT的存在性与有效性
    	if ($this->checkSsoTicket()) {
    		//获取用户信息，存入ASO域空间cookie
    		$userInfo = $this->gc('userInfo','');
    		//SSOT有效，生成ASOT,转向App页面
			$asotKey = 65535;
			$asot = md5($asotKey * intval($userInfo));
			//cookie定时失效，以确保对SSO登录状态的检查
			$this->sc($asotName,$asot,60,'/');
			return true;
    	}
		else {
			//SSOT无效，转向SSO系统
	    	$asoUrl = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
			$this->_redirect($this->view->host('sso') . '/sso/index/login?asoUrl=' . urlencode($asoUrl));
			return true;
		}
    }
    
    /**
     * 执行注销登录操作
     *
     */
    public function asoLogout() {
    	$asotName = 'ASOT_' . md5($_SERVER['HTTP_HOST']);
    	$ssotName = 'SSOT';
    	//清除ASO域空间cookie
    	$this->sc('userInfo','',time(),'/');
    	$this->sc($asotName,'',time(),'/');
    	$this->sc($ssotName,'',time(),'/');
    	//清除ASO域空间session
    	//重新生成并记录当前url，转向SSO系统
    	$hr = parse_url($_SERVER['HTTP_REFERER']);
    	$asoUrl = "http://{$hr['host']}{$hr['path']}";
		$this->_redirect($this->view->host('sso') . '/sso/index/logout?asoUrl=' . urlencode($asoUrl));
    }
    
	/**
     * 判断ASOT是否有效
     *
     * @param string $asotName 指定当前App应用ASOT名称的字符串
     * @return boolean
     */
    protected function checkAsoTicket($asotName = 'ASOT_z') {
    	$asot = $this->gc($asotName,'');
    	if ('' == $asot) {
    		return false;
    	}
    	else {
    		return true;
    	}
    }
    
    /**
     * 判断SSOT是否存在
     *
     * @return boolean
     */
    protected function checkSsoTicket($ssotName = 'SSOT') {
    	//获取ASO域空间cookie或requst中的SSOT
    	$ssot = $this->gr($ssotName,'');
    	if ('' == $ssot) {
    		//ssot不存在，返回false
			return false;
    	}
    	else {
    		//判断ssto有效性，连接
			$client = new Zend_Http_Client($this->view->host('sso') . '/sso/service');
			$client->setMethod(Zend_Http_Client::POST);
			$client->setHeaders('username','test');
			$client->setHeaders('password','test');
			$client->setHeaders('function',3);
			//发送指令
			$data = array('SSOT'=>$ssot);
			$client->setRawData(Zend_Json::encode($data));
			$response = $client->request();
			$result = Zend_Json::decode($response->getBody());
//			var_dump($result);exit;
			//
			if (301 == $result['code']) {
				//存入cookie
				$this->sc($ssotName,$ssot,time(),'/');
				$this->sc('userInfo',$result['userInfo'],time(),'/');
				//存入session，临时测试
				$s = new Zend_Session_Namespace('SSO');
				$s->SSOT = $ssot;
				$s->userInfo = $result['userInfo'];
				return true;
			}
			else {
				return false;
			}
    	}
    }
}
